import { getDB } from '../db/connection.js';

class ComponentVersion {
  static async getAll() {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM component_versions');
    return rows;
  }

  static async getById(id) {
    const db = await getDB();
    const [rows] = await db.execute('SELECT * FROM component_versions WHERE id = ?', [id]);
    return rows.length > 0 ? rows[0] : null;
  }

  static async getByComponentId(componentId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM component_versions WHERE component_id = ? ORDER BY created_at DESC',
      [componentId]
    );
    return rows;
  }

  static async getActiveByComponentId(componentId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM component_versions WHERE component_id = ? AND is_active = true',
      [componentId]
    );
    return rows.length > 0 ? rows[0] : null;
  }

  static async create(componentId, version, content, isActive = false) {
    const db = await getDB();
    const [result] = await db.execute(
      'INSERT INTO component_versions (component_id, version, content, is_active) VALUES (?, ?, ?, ?)',
      [componentId, version, JSON.stringify(content), isActive]
    );
    return result.insertId;
  }

  static async update(id, data) {
    const db = await getDB();
    const fields = Object.keys(data);
    const values = Object.values(data);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    await db.execute(
      `UPDATE component_versions SET ${setClause} WHERE id = ?`,
      [...values, id]
    );
    
    return this.getById(id);
  }

  static async setActive(id) {
    const db = await getDB();
    // 先将该组件的所有版本设为非激活
    await db.execute(
      'UPDATE component_versions SET is_active = false WHERE component_id = (SELECT component_id FROM component_versions WHERE id = ?)',
      [id]
    );
    // 再将指定版本设为激活
    await db.execute(
      'UPDATE component_versions SET is_active = true WHERE id = ?',
      [id]
    );
    return this.getById(id);
  }

  static async delete(id) {
    const db = await getDB();
    await db.execute('DELETE FROM component_versions WHERE id = ?', [id]);
  }
}

export default ComponentVersion;
